<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>基于模板生成文档 - DocuGen</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/static/css/vendor/jsoneditor.min.css">
    <link rel="stylesheet" href="/static/css/common.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-file-earmark-text me-2"></i>DocuGen
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/"><i class="bi bi-house me-1"></i>首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/document-generator"><i class="bi bi-file-earmark-text me-1"></i>文档生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/template-generator"><i class="bi bi-file-earmark-richtext me-1"></i>基于模板生成文档</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/qa"><i class="bi bi-chat-dots me-1"></i>智能问答</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="modelDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-gear me-1"></i>模型设置
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="modelDropdown">
                            <li><a class="dropdown-item model-switch" data-model="local" href="#"><i class="bi bi-cpu me-1"></i>本地模型</a></li>
                            <li><a class="dropdown-item model-switch" data-model="third_party" href="#"><i class="bi bi-cloud me-1"></i>第三方模型</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="container py-4">
            <div class="page-header">
                <h1 class="page-title"><i class="bi bi-file-earmark-richtext"></i>基于模板生成文档</h1>
            </div>
        
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="card-title mb-0">
                                <i class="bi bi-file-earmark-code me-2"></i>
                                生成选项
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <label class="form-label" for="templateType">文档类型</label>
                                    <select class="form-select" id="templateType">
                                        <option value="contract">合同文档</option>
                                        <option value="report">报告文档</option>
                                        <option value="proposal">提案文档</option>
                                        <option value="policy">政策文档</option>
                                        <option value="custom">自定义文档</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <label class="form-label" for="templateDescription">文档需求描述</label>
                                    <textarea class="form-control" id="templateDescription" rows="3" placeholder="请描述您需要生成的文档内容、结构和用途..."></textarea>
                                </div>
                            </div>
                            
                            <!-- RAG选项 -->
                            <div class="rag-options">
                                <h6 class="rag-options-title">
                                    <div class="feature-icon">
                                        <i class="bi bi-database"></i>
                                    </div>
                                    知识库增强
                                </h6>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="useRag" checked>
                                    <label class="form-check-label" for="useRag">使用RAG增强文档质量</label>
                                </div>
                                <div class="row">
                                    <div class="col-md-8">
                                        <select class="form-select" id="ragSource" disabled>
                                            <option value="">加载知识库中...</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <button class="btn btn-outline-primary w-100" id="refreshKbBtn">
                                            <i class="bi bi-arrow-clockwise"></i> 刷新列表
                                        </button>
                                    </div>
                                </div>
                                <div class="mt-3" id="customRagSection" style="display: none;">
                                    <textarea class="form-control" id="customRagInput" rows="2" placeholder="输入自定义知识库内容，用于增强文档质量"></textarea>
                                </div>
                            </div>
                            
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <label class="form-label" for="templateFormat">输出格式</label>
                                    <select class="form-select" id="templateFormat">
                                        <option value="markdown">Markdown</option>
                                        <option value="html">HTML</option>
                                        <option value="json">JSON</option>
                                        <option value="text">纯文本</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <button class="btn btn-primary w-100" id="generateBtn">
                                        <i class="bi bi-magic me-2"></i>生成文档
                                    </button>
                                </div>
                            </div>
                            
                            <div id="resultSection" style="display: none;">
                                <hr>
                                <h5 class="mb-3">生成结果</h5>
                                <div class="alert alert-success mb-3" role="alert">
                                    <i class="bi bi-check-circle-fill me-2"></i>
                                    文档生成成功！您可以复制下方内容或下载文件。
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-6 mb-2 mb-md-0">
                                        <button class="btn btn-outline-primary w-100" id="copyBtn">
                                            <i class="bi bi-clipboard me-2"></i>复制内容
                                        </button>
                                    </div>
                                    <div class="col-md-6">
                                        <button class="btn btn-outline-success w-100" id="downloadBtn">
                                            <i class="bi bi-download me-2"></i>下载文件
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="card">
                                    <div class="card-header bg-light">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span>文档预览</span>
                                            <div class="form-check form-switch" id="renderMarkdownContainer">
                                                <input class="form-check-input" type="checkbox" id="renderMarkdown" checked>
                                                <label class="form-check-label" for="renderMarkdown">渲染Markdown</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div id="templateResult" class="p-3 bg-light rounded" style="max-height: 500px; overflow-y: auto;"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="text-white py-4">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="bi bi-file-earmark-text me-2"></i>DocuGen</h5>
                    <p>AI驱动的文档生成系统，让创作更高效。</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="mb-0">&copy; 2023 DocuGen. 保留所有权利。</p>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsoneditor@9.9.0/dist/jsoneditor.min.js"></script>
    <script>
        $(document).ready(function() {
            const templateGenerator = {
                config: {
                    currentModel: 'third_party',
                    api: {
                        listKb: '/api/kb/list',
                        generate: '/api/generate-template',
                        switchModel: '/api/switch-model'
                    }
                },
                state: {
                    jsonEditor: null,
                    generatedContent: '',
                    generatedFormat: ''
                },
                els: {
                    templateType: $('#templateType'),
                    templateDescription: $('#templateDescription'),
                    templateFormat: $('#templateFormat'),
                    useRag: $('#useRag'),
                    ragSource: $('#ragSource'),
                    customRagSection: $('#customRagSection'),
                    customRagInput: $('#customRagInput'),
                    generateBtn: $('#generateBtn'),
                    refreshKbBtn: $('#refreshKbBtn'),
                    copyBtn: $('#copyBtn'),
                    downloadBtn: $('#downloadBtn'),
                    resultSection: $('#resultSection'),
                    resultContainer: $('#templateResult'),
                    renderMarkdownSwitch: $('#renderMarkdown'),
                    renderMarkdownContainer: $('#renderMarkdownContainer'),
                    modelSwitchers: $('.model-switch')
                },

                init: function() {
                    this.bindEvents();
                    this.loadKnowledgeBases();
                    this.handleFormatChange();
                },

                bindEvents: function() {
                    this.els.useRag.on('change', this.handleRagToggle.bind(this));
                    this.els.ragSource.on('change', this.handleRagSourceChange.bind(this));
                    this.els.refreshKbBtn.on('click', this.loadKnowledgeBases.bind(this));
                    this.els.generateBtn.on('click', this.handleGenerate.bind(this));
                    this.els.renderMarkdownSwitch.on('change', this.renderResult.bind(this));
                    this.els.copyBtn.on('click', this.copyResult.bind(this));
                    this.els.downloadBtn.on('click', this.downloadResult.bind(this));
                    this.els.modelSwitchers.on('click', this.handleModelSwitch.bind(this));
                    this.els.templateFormat.on('change', this.handleFormatChange.bind(this));
                },

                handleRagToggle: function() {
                    const useRag = this.els.useRag.is(':checked');
                    this.els.ragSource.prop('disabled', !useRag);
                    this.handleRagSourceChange();
                },

                handleRagSourceChange: function() {
                    const useRag = this.els.useRag.is(':checked');
                    const isCustom = this.els.ragSource.val() === 'custom';
                    this.els.customRagSection.toggle(useRag && isCustom);
                },

                handleFormatChange: function() {
                    const isMarkdown = this.els.templateFormat.val() === 'markdown';
                    this.els.renderMarkdownContainer.toggle(isMarkdown);
                },

                handleGenerate: function() {
                    const description = this.els.templateDescription.val().trim();
                    if (!description) {
                        return this.showAlert('请输入文档需求描述', 'warning');
                    }

                    this.toggleGenerateButton(true);
                    const useRag = this.els.useRag.is(':checked');
                    const ragSource = useRag ? this.els.ragSource.val() : '';
                    const format = this.els.templateFormat.val();

                    const payload = {
                        template_type: this.els.templateType.val(),
                        description: description,
                        format: format,
                        enable_rag: useRag,
                        kb_name: ragSource,
                        custom_rag_content: (useRag && ragSource === 'custom') ? this.els.customRagInput.val().trim() : ''
                    };

                    $.ajax({
                        url: this.config.api.generate,
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(payload),
                        success: (response) => {
                            if (response.success) {
                                this.state.generatedContent = response.data;
                                this.state.generatedFormat = format;
                                this.renderResult();
                            } else {
                                this.showAlert('生成失败: ' + (response.error || '未知错误'), 'danger');
                            }
                        },
                        error: (xhr) => this.showAlert('请求失败: ' + xhr.responseText, 'danger'),
                        complete: () => this.toggleGenerateButton(false)
                    });
                },

                handleModelSwitch: function(e) {
                    e.preventDefault();
                    const modelType = $(e.currentTarget).data('model');
                    if (modelType === this.config.currentModel) return;

                    $.ajax({
                        url: this.config.api.switchModel,
                        type: 'POST',
                        data: { model_type: modelType },
                        success: (response) => {
                            if (response.success) {
                                this.config.currentModel = modelType;
                                const modelName = modelType === 'local' ? '本地模型' : '第三方模型';
                                this.showAlert(`已切换到${modelName}`, 'success');
                            } else {
                                this.showAlert('模型切换失败: ' + (response.error || '未知错误'), 'danger');
                            }
                        },
                        error: (xhr) => this.showAlert('模型切换请求失败: ' + xhr.responseText, 'danger')
                    });
                },

                loadKnowledgeBases: function() {
                    this.els.ragSource.html('<option value="">加载知识库中...</option>').prop('disabled', true);
                    $.ajax({
                        url: this.config.api.listKb,
                        type: 'GET',
                        success: (response) => {
                            if (response.success && response.data) {
                                const $select = this.els.ragSource;
                                $select.empty().append('<option value="custom">自定义知识库内容</option>');
                                if (Array.isArray(response.data) && response.data.length > 0) {
                                    response.data.forEach(kb => $select.append(`<option value="${kb}">${kb}</option>`));
                                } else {
                                    $select.append('<option value="" disabled>没有可用的知识库</option>');
                                }
                                this.handleRagToggle();
                            } else {
                                this.showAlert("获取知识库列表失败: " + (response.error || '未知错误'), 'danger');
                                this.els.ragSource.html('<option value="">加载知识库失败</option>');
                            }
                        },
                        error: (xhr, status, error) => {
                            this.showAlert("请求知识库列表失败", 'danger');
                            console.error("请求知识库列表失败:", status, error);
                            this.els.ragSource.html('<option value="">加载知识库失败</option>');
                        }
                    });
                },

                toggleGenerateButton: function(isLoading) {
                    if (isLoading) {
                        this.els.generateBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>生成中...');
                    } else {
                        this.els.generateBtn.prop('disabled', false).html('<i class="bi bi-magic me-2"></i>生成文档');
                    }
                },

                renderResult: function() {
                    const { generatedContent, generatedFormat } = this.state;
                    const $container = this.els.resultContainer;
                    $container.empty();
                    this.handleFormatChange();

                    switch (generatedFormat) {
                        case 'markdown':
                            if (this.els.renderMarkdownSwitch.is(':checked')) {
                                $container.html(marked.parse(generatedContent));
                            } else {
                                $container.html(`<pre><code>${this.escapeHtml(generatedContent)}</code></pre>`);
                            }
                            break;
                        case 'json':
                            try {
                                const jsonContent = typeof generatedContent === 'string' ? JSON.parse(generatedContent) : generatedContent;
                                if (this.state.jsonEditor) this.state.jsonEditor.destroy();
                                this.state.jsonEditor = new JSONEditor($container[0], { mode: 'view', mainMenuBar: false, navigationBar: false });
                                this.state.jsonEditor.set(jsonContent);
                            } catch (e) {
                                $container.html(`<pre><code>${this.escapeHtml(String(generatedContent))}</code></pre>`);
                            }
                            break;
                        case 'html':
                            const iframe = document.createElement('iframe');
                            iframe.style.width = '100%';
                            iframe.style.height = '400px';
                            iframe.style.border = 'none';
                            iframe.srcdoc = generatedContent;
                            $container.append(iframe);
                            break;
                        default:
                            $container.html(`<pre><code>${this.escapeHtml(generatedContent)}</code></pre>`);
                    }

                    this.els.resultSection.show();
                    $('html, body').animate({ scrollTop: this.els.resultSection.offset().top - 100 }, 500);
                },

                getContentForAction: function() {
                    const { generatedFormat, generatedContent, jsonEditor } = this.state;
                    switch (generatedFormat) {
                        case 'json':
                            return jsonEditor ? JSON.stringify(jsonEditor.get(), null, 2) : String(generatedContent);
                        case 'html':
                            const iframe = this.els.resultContainer.find('iframe')[0];
                            return iframe ? iframe.contentDocument.documentElement.outerHTML : generatedContent;
                        default:
                            return generatedContent;
                    }
                },

                copyResult: function() {
                    navigator.clipboard.writeText(this.getContentForAction()).then(
                        () => this.showAlert('内容已复制到剪贴板', 'success'),
                        (err) => {
                            this.showAlert('复制失败，请手动操作', 'danger');
                            console.error('复制失败:', err);
                        }
                    );
                },

                downloadResult: function() {
                    const content = this.getContentForAction();
                    const format = this.state.generatedFormat;
                    const mimeTypes = { markdown: 'text/markdown', json: 'application/json', html: 'text/html', text: 'text/plain' };
                    const extensions = { markdown: 'md', json: 'json', html: 'html', text: 'txt' };
                    const blob = new Blob([content], { type: mimeTypes[format] || 'text/plain' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `document.${extensions[format] || 'txt'}`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                },

                escapeHtml: (unsafe) => unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"),
                
                showAlert: (message, type = 'info') => alert(message)
            };

            templateGenerator.init();
        });
    </script>
</body>
</html>